// 库函数
#include <stdio.h>
#include <stdbool.h>
#include "FreeRTOS.h"
#include "task.h"
#include "cmsis_os2.h"
// hal库函数
#include "main.h"
// 自定义函数
#include "pwmLedTask.h"

extern osEventFlagsId_t pwmBtnEvent; // PWM灯按键事件标志
extern TIM_HandleTypeDef htim13;

static uint8_t g_duty_value = DEFAULT_DUTY_VALUE; // 占空比值

/* 接口函数 */
void SetPwmDuty(uint8_t duty)
{
    if (duty > htim13.Init.Period)
    {
        duty = htim13.Init.Period; // 最大自动重装载寄存器
    }
    g_duty_value = duty;
    printf("[SetPwmDuty] Change the duty cycle to: %d\r\n", duty);
}

/* 任务函数 */
static void PwmLedTask(void *argument)
{
    (void)argument;

    uint32_t flags;
    GPIO_PinState readPin;
    bool isLedOn = false;

    HAL_TIM_PWM_Start(&htim13, TIM_CHANNEL_1); // 启用PWM信号

    while (1)
    {
        flags = osEventFlagsWait(pwmBtnEvent, 0X0001, osFlagsWaitAny, osWaitForever);

        if (flags & 0X0001)
        {
            osDelay(10); // 按键按下消抖

            // 等待按键释放
            do
            {
                osDelay(10);
                readPin = HAL_GPIO_ReadPin(PWM_BTN_GPIO_Port, PWM_BTN_Pin);
            } while (readPin == GPIO_PIN_RESET);

            osDelay(10); // 按键释放消抖

            if (isLedOn)
            {
                __HAL_TIM_SET_COMPARE(&htim13, TIM_CHANNEL_1, 0);
                printf("[PwmLedTask] PwmLED is off!\r\n");
            }
            else
            {
                __HAL_TIM_SET_COMPARE(&htim13, TIM_CHANNEL_1, g_duty_value);
                printf("[PwmLedTask] PwmLED is on! Duty is %d.\r\n", g_duty_value);
            }

            isLedOn = !isLedOn; // 切换状态

            osEventFlagsClear(pwmBtnEvent, 0X0001); // 清除事件标志
        }
    }
}

/* 入口函数 */
void PwmLedTaskEnter(void)
{
    osThreadAttr_t attr = {
        .name = "PwmLedTask",
        .stack_size = 1024,
        .priority = (osPriority_t)osPriorityNormal,
    };

    if (osThreadNew((osThreadFunc_t)PwmLedTask, (void *)NULL, &attr) == NULL)
    {
        printf("[PwmLedTaskEnter] Failed to cerate PwmLed task!\r\n");
        osEventFlagsDelete(pwmBtnEvent); // 删除事件标志
    }
}
